package com.zdyl.springboot_shiro.shiro.realms;



import com.zdyl.springboot_shiro.domain.User;
import com.zdyl.springboot_shiro.service.UserService;
import com.zdyl.springboot_shiro.shiro.utils.JwtToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义realm
 */
public class CustomerRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //设置realm的名称
    @Override
    public void setName(String name) {
        super.setName("customRealm");
    }

    /***
     *
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进来了授权");

        //给资源进行授权
       SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

       //添加资源的授权字符串
       /* info.addStringPermission("user:add");*/
        //到数据库查询当前登录用户的授权字符串
        //获取当前登录用户
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        User dbuser = userService.findById(user.getId());
        info.addStringPermission(dbuser.getPerms());

        return info;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("进来了认证");
       // JwtToken jwtToken = (JwtToken) authenticationToken;

        //编写shiro判断逻辑,判断用户名和密码
        //1.判断用户名
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = userService.findByName(token.getUsername());
        if(user == null){
             //用户不存在
             return null ;
         }
         //2.判断密码
      return new SimpleAuthenticationInfo(user,user.getPassword(),"");

    }
}
